package com.hanxiaozhang.hash;

import java.util.LinkedList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 〈一句话功能简述〉<br>
 * 〈一致性哈希，不考虑各个机器的性能〉
 *
 * @author hanxinghua
 * @create 2022/12/29
 * @since 1.0.0
 */
public class ConsistencyHashing {


    public static void main(String[] args) {

        // 模拟客户端的请求
        String[] nodes = { "127.0.0.1", "10.9.3.253", "192.168.10.1" };

        System.out.println("---- ---- ---- ---- ----");
        for (String node : nodes) {
            System.out.println("[" + node + "]的hash值为" + getHash(node) + ", 被路由到结点[" + getServer(node) + "]");
        }
        System.out.println("---- ---- ---- ---- ----");

        // 模拟服务器上线
        addNode("192.168.1.7");
        // 模拟服务器下线
        delNode("192.168.1.2");

        System.out.println("---- ---- ---- ---- ----");
        for (String node : nodes) {
            System.out.println("[" + node + "]的hash值为" + getHash(node) + ", 被路由到结点[" + getServer(node) + "]");
        }
        System.out.println("---- ---- ---- ---- ----");
    }



    /**
     * 虚拟节点的个数
     */
    private static final int VIRTUAL_NUM = 5;

    /**
     * 虚拟节点分配，key是hash值，value是虚拟节点服务器名称
     */
    private static final SortedMap<Integer, String> SHARDS = new TreeMap();

    /**
     * 真实节点列表
     */
    private static final List<String> REAL_NODES = new LinkedList();

    /**
     * 模拟初始服务器
     */
    private static final String[] SERVERS = { "192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.5", "192.168.1.6" };


    /**
     * 初始化数据
     */
    static {
        for (String server : SERVERS) {
            addNode(server);
        }
    }

    /**
     * 获取被分配的节点名
     *
     * @param key
     * @return
     */
    public static String getServer(String key) {
        int hash = getHash(key);
        Integer node = null;
        SortedMap<Integer, String> subMap = SHARDS.tailMap(hash);
        if (subMap.isEmpty()) {
            node = SHARDS.lastKey();
        } else {
            node = subMap.firstKey();
        }
        String virtualNode = SHARDS.get(node);
        return virtualNode.substring(0, virtualNode.indexOf("&&"));
    }

    /**
     * 添加节点
     *
     * @param node
     */
    public static void addNode(String node) {
        if (!REAL_NODES.contains(node)) {
            REAL_NODES.add(node);
            System.out.println("真实节点[" + node + "] 上线添加");
            for (int i = 0; i < VIRTUAL_NUM; i++) {
                String virtualNode = node + "&&VN" + i;
                int hash = getHash(virtualNode);
                SHARDS.put(hash, virtualNode);
                System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + " 被添加");
            }
        }
    }

    /**
     * 删除节点
     *
     * @param node
     */
    public static void delNode(String node) {
        if (REAL_NODES.contains(node)) {
            REAL_NODES.remove(node);
            System.out.println("真实节点[" + node + "] 下线移除");
            for (int i = 0; i < VIRTUAL_NUM; i++) {
                String virtualNode = node + "&&VN" + i;
                int hash = getHash(virtualNode);
                SHARDS.remove(hash);
                System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + " 被移除");
            }
        }
    }

    /**
     * FNV1_32_HASH算法
     */
    private static int getHash(String str) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < str.length(); i++) {
            hash = (hash ^ str.charAt(i)) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        // 如果算出来的值为负数则取其绝对值
        if (hash < 0) {
            hash = Math.abs(hash);
        }
        return hash;
    }

}
